using System.Collections;
using System.Text;
using OrbitOne.GoogleCustomSearch.QueryParameters;

namespace OrbitOne.GoogleCustomSearch
{
   public class RequestParameterBuilder
   {
       private static string[] ESSENTIAL_SEARCH_PARAMETERS  = new string[]{"q","as_q"};
       #region Properties

       private bool canSearch = false;
       private ArrayList queryParemeters;

      

       public bool CanSearch
       {
           get { return canSearch; }
           set { canSearch = value; }
       }

       #endregion Properties
       #region Constructor
       public RequestParameterBuilder()
       {
           this.queryParemeters = new ArrayList();
           
       }
       #endregion Constructor

       #region Methods

       public void Add(QueryParameter parameter)
       {
           if(!CanSearch)
           {
               CanSearch = IsEssential(parameter);
           }
           foreach (QueryParameter param in queryParemeters)
           {
               if (param.Name == parameter.Name)
               {
                   queryParemeters.Remove(param);
                   queryParemeters.Add(parameter);
                   return;
               }
           }

           queryParemeters.Add(parameter);
       }
       private bool IsEssential(QueryParameter parameter)
       {
          foreach(string str in ESSENTIAL_SEARCH_PARAMETERS )
          {
              if(parameter.Name==str)
              {
                  return true;
                  
              }
          }
           return false;
       }

       /// <summary>
       /// Client, cx,output are required
       /// </summary>
       public void AddRequiredQueryParameter()
       {
           CX cx = new CX();
           cx.Value = System.Configuration.ConfigurationSettings.AppSettings["GoogleCustomSearchEngine"];
           Add(cx);

           Add(new Client());
           Add(new Output());
       }
       
       public string Build()
       {
           AddRequiredQueryParameter();
           StringBuilder result = new StringBuilder("?");
           foreach(QueryParameter parameter in this.queryParemeters)
           {
               result.AppendFormat("{0}&",parameter.Format());
           }
           result.Remove(result.Length - 1, 1);
           return result.ToString();
       }
       
       #endregion Methods

   }
}
